package org.xuyuji.DBtoBean.createFile;

import java.io.File;
import java.io.FileWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.xuyuji.DBtoBean.data.TableInfo;

public abstract class CreateFile {
	private static final String PROPERTIES_PATH = "./src/main/resources/velocity.properties";
	
	private String templatePath;
	private String outputFolderPath;
	private String fileType;
	
	public CreateFile(String templatePath, String outputFolderPath, String fileType) {
		this.templatePath = templatePath;
		this.outputFolderPath = outputFolderPath;
		this.fileType = fileType;
	}
	
	public void create(String tableName) throws Exception{
		log("开始处理" + tableName);
		createBean(tableName);
		log("处理" + tableName + "完成");
	}
	
	private void createBean(String tableName) throws Exception{
		TableInfo tableInfo = TableInfo.valueOf(tableName);
		
		Velocity.init(PROPERTIES_PATH);
		Template template = Velocity.getTemplate(templatePath);
		VelocityContext context = new VelocityContext();
		context.put("tableInfo", tableInfo);
		
		File beanFolder = new File(outputFolderPath);
		if(!beanFolder.exists()){
			beanFolder.mkdirs();
		}
		
		FileWriter writer = new FileWriter(new File(outputFolderPath + tableInfo.getClassName() + "." + fileType));
		template.merge(context, writer);
		writer.close();
	}
	
	protected abstract void log(String log);
}
